<?php

class ZFPainel_View_Helper_TelaIncludes extends Zend_View_Helper_Abstract
{

    /**
     *
     * @var Zend_View_Helper_HeadLink
     */
    private $headLink;

    /**
     *
     * @var Zend_View_Helper_HeadScript
     */
    private $headScript;
    private $initialized = false;

    public function __toString()
    {
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            return $this->toString();
        }
        return '';
    }

    private function init()
    {
        $this->headScript = new Zend_View_Helper_HeadScript();
        $this->headScript->setView($this->view);

        $this->headLink = new Zend_View_Helper_HeadLink();
        $this->headLink->setView($this->view);
    }
    
    public function getHeadScript()
    {
        return $this->headScript;
    }
    
    public function getHeadLink()
    {
        return $this->headLink;
    }

    public function renderLayout()
    {
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            return '';
        }
        return $this->toString();
    }

    public function telaIncludes()
    {
        if (!$this->initialized) {
            $this->init();
        }

        return $this;
    }

    public function toString()
    {
        $request = Zend_Controller_Front::getInstance()->getRequest();
        
        $fileJs1 = '/lib/painel/js/telas/'
                . $request->getParam('strategyController')
                . '.js';

        $fileJs2 = '/lib/painel/js/telas/'
                . $request->getParam('strategyController')
                . '/'
                . $request->getParam('strategyAction')
                . '.js';
        
        if (file_exists(PATH_PUBLIC . $fileJs1)) {
            $this->headScript->appendFile($fileJs1);
        }

        if (file_exists(PATH_PUBLIC . $fileJs2)) {
            $this->headScript->appendFile($fileJs2);
        }
        
        $fileCss1 = '/lib/painel/css/telas/'
                . $request->getParam('strategyController')
                . '/'
                . $request->getParam('strategyAction')
                . '.css';
        
        if (file_exists(PATH_PUBLIC . $fileCss1)) {
            $this->headLink->appendStylesheet($fileCss1, 'all');
        }
        
        return $this->headLink->toString() . $this->headScript->toString();
    }

}
